import { createStore } from 'vuex'
// 刷新页面, 购物车数据会丢失, 因为 vue 刷新后会重新创建 vue 实例,
// 因此 store 会被重新赋值, 所以我们需要把购物车的信息放到 localStorage 里面
// 把购物车放入缓存
const setLocalCartData = (state) => {
  // 把购物相关数据解构出来/获取购物车数据
  const { cartData } = state
  // 对象转json字符串
  const cartDataString = JSON.stringify(cartData)
  // 保存到localStorage
  localStorage.cartData = cartDataString
}

// 从缓存中获取购物车数据
const getLocalCartData = () => {
  let result = {}
  // 判断localStorage里面是否有数据
  if (localStorage.cartData) {
    result = JSON.parse(localStorage.cartData)
  }
  // 返回数据
  return result
}
export default createStore({
  state: {
    // 从缓存获取数据
    cartData: getLocalCartData()
  },
  mutations: {
    changeItemToCart (state, payload) {
      const { shopId, shopName, itemId, itemInfo, num } = payload
      // 判断有没有shopId
      let shopInfo = {}
      if (state.cartData[shopId]) {
        shopInfo = state.cartData[shopId]
      } else {
        shopInfo.shopName = shopName
        shopInfo.itemList = {}
      }

      // 购物车的商品信息
      let item = null
      if (shopInfo.itemList[itemId]) {
        item = shopInfo.itemList[itemId]
      } else {
        item = itemInfo
        item.count = 0
      }

      // 数量改变
      item.count += num
      // 如果为空，则从购物车中移除
      if (item.count === 0) {
        // 从shopInfo中删除item
        delete shopInfo.itemList[itemId]
      } else {
        // 把勾选状态改为true
        item.checked = true
        // 把item加到shopInfo中
        shopInfo.itemList[itemId] = item
      }
      //  判断店铺下的购物车是否为空
      if (JSON.stringify(shopInfo.itemList) !== '{}') {
        // 把shopInfo加到cartData
        state.cartData[shopId] = shopInfo
      } else {
        // 清除商铺信息
        delete state.cartData[shopId]
      }
      setLocalCartData(state)
    },
    changeItemChecked (state, payload) {
      const { shopId, itemId } = payload
      const item = state.cartData[shopId].itemList[itemId]
      item.checked = !item.checked
      setLocalCartData(state)
    },
    clearCart (state, payload) {
      const { shopId } = payload
      state.cartData[shopId].itemList = {}
      setLocalCartData(state)
    },
    setAllChecked (state, payload) {
      const { shopId, checked } = payload
      const shopInfo = state.cartData[shopId]
      if (checked) { for (const key in shopInfo.itemList) { shopInfo.itemList[key].checked = true } } else {
        for (const key in shopInfo.itemList) { shopInfo.itemList[key].checked = false }
      }
      setLocalCartData(state)
    }
  },
  actions: {},
  modules: {}
})
